package com.hk.Mgr.web.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.Mgr.web.message.kyc.UserExtralDetailExcelRes;
import com.hk.Mgr.web.message.kyc.UserExtralExcelRes;
import com.hk.Mgr.web.message.kyc.UserExtralReq;
import com.hk.Mgr.web.message.kyc.UserExtralRes;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.ExcelHelper;
import com.hk.commons.HqlFilter;
import com.hk.commons.ReqToModelHelper;
import com.hk.commons.StringHelper;
import com.hk.commons.entity.Organization;
import com.hk.commons.entity.UserExtraInfo;
import com.hk.commons.entity.sys.SysUser;
import com.hk.service.IOrganization;
import com.hk.service.IUserExtraInfo;
import com.hk.service.kyc.IPoints;
import com.hk.service.sys.ISysUser;

/**
 * @author lemon 用户实现类
 */
@Controller
@RequestMapping(value = BaseCtrl.MgrRootPath + "/userPointsDetailCtrl")
public class UserPointsDetailCtrl extends BaseCtrl {

	@Autowired
	private ISysUser userService;

	@Autowired
	private IPoints pointsService;

	@Autowired
	private IUserExtraInfo userExtraInfoService;

	@Autowired
	private IOrganization orgService;

	/**
	 * 增加积分规则
	 * 
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	public ResponseBase<List<UserExtralDetailExcelRes>> list(
			@RequestBody UserExtralReq req) {
		ResponseBase<List<UserExtralDetailExcelRes>> resp = new ResponseBase<List<UserExtralDetailExcelRes>>();
		List<UserExtralDetailExcelRes> respInfoList = new ArrayList<UserExtralDetailExcelRes>();
		 
		try {
			String userName = req.getUserRealName();

			String finName = req.getFinRealName();

			Integer channel = req.getChannel();

			logger.info("mgr/userPointsDetailCtrl/list userName = " + userName
					+ " finName = " + finName + "  channel =  " + channel);

			HqlFilter hqlFilter = new HqlFilter();
			hqlFilter = getInfoList(req.getUserPhoneNum(), req.getFinRealName(), channel);

			List<SysUser> userAllSize = userService.findByFilter(hqlFilter);
			
			if(req.getPageSize() < 50){
				// 获取用户列表
				List<SysUser> userList = userService.findByFilter(hqlFilter,
					req.getCurPage(), req.getPageSize());
				// 填充数据
				respInfoList = getInfoList(userList);
			}else{
				respInfoList.add(new UserExtralDetailExcelRes());
			}
			
			resp.setResult(respInfoList);
			resp.setSize(userAllSize.size());
			resp.setResultCode(StatusCode.SUCCESS.key());
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * 导出所有的数据
	 * 
	 * @author jeff
	 * @return
	 */
	@RequestMapping(value = "/excel")
	@ResponseBody
	public void excelExport(HttpServletRequest request,
			HttpServletResponse response, @RequestParam String userPhoneNum, @RequestParam String finRealName,
			@RequestParam Integer orgId) {

		HqlFilter hqlFilter = getInfoList(userPhoneNum, finRealName, orgId);

		 
		// 获取用户列表
		List<SysUser> userList = userService.findByFilter(hqlFilter);

		 
		// 填充数据
		List<UserExtralDetailExcelRes> respInfoList = getInfoList(userList);
		
		String head = "用户id, 手机号,  是否绑卡, 理财师姓名,手机号,职务,部门  ";
		ExcelHelper newExcel = new ExcelHelper(respInfoList, head);
		Workbook wb = newExcel.outputExcel();
		response.setContentType("application/vnd.ms-excel");
		String titlename = "用户绑卡信息明细";
		try {
			response.setHeader("Content-disposition", "attachment; filename="
					+ new String((titlename).getBytes("gbk"), "iso8859-1")
					+ ".xlsx");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		OutputStream ouputStream;
		try {
			ouputStream = response.getOutputStream();
			wb.write(ouputStream);
			ouputStream.flush();
			ouputStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 根据条件获取用户列表
	 *
	 * @return
	 */
	private HqlFilter getInfoList(String userPhoneNum, String finName , Integer channel) {
		logger.info("mgr/PointsCtl/list userPhoneNum = " + userPhoneNum + " finName = "
				+ finName + "  channel =  " + channel);

		HqlFilter hqlFilter = new HqlFilter();
		
		hqlFilter.addSql(" where 1=1 ");
		
		// 如果用户姓名不为空则优先按照用户姓名进行排序
		if (StringHelper.isNotEmpty(userPhoneNum)) {
			
			hqlFilter
			.addSql(" and id in ( select id  from  SysUser where name like '%"
					+ userPhoneNum
					+ "%\' "
					+ "or RealName like  '%"
					+ userPhoneNum + "%\') ");
		}

		if (StringHelper.isNotEmpty(finName)) {
			// 如果理财师的名字不为空，则优先按照理财师的姓名进行排序
			SysUser finUser = userService.getUserByRealName(finName);
			if (finUser != null) {
				hqlFilter.addEQFilter("recommendCode", finUser.getName());
			}
		}

		if (channel != null) {
			String  sqlFilter = " and id  in ( select id from com.hk.commons.entity.sys.SysUser where channel = "+ channel +")";
			hqlFilter.addSql(sqlFilter);
		}
		
		//logger.info("all filter = " + hqlFilter.getWhereAndOrderHql());

		return hqlFilter;
	}

	/**
	 * 获取返回结果
	 * 
	 * @param userList
	 * @return
	 */
	private List<UserExtralDetailExcelRes> getInfoList(List<SysUser> userList) {
		List<UserExtralDetailExcelRes> infoList = new ArrayList<UserExtralDetailExcelRes>();

		for (SysUser user : userList) {
			UserExtralDetailExcelRes resInfo = new UserExtralDetailExcelRes();
			resInfo.setCol010userId(user.getId().toString());
			resInfo.setCol020userPhoneNum(user.getName().toString());
			
			if(user.getTieCard() != null && user.getTieCard() == 1){
				resInfo.setCol030isTieCard("是");
			}
			SysUser finUser = userService
					.getByPhoneNum(user.getRecommendCode());
			if (finUser != null) {
				resInfo.setCol040finName(finUser.getRealName());
				resInfo.setCol050finPhoneNum(finUser.getName());
				if (finUser.getOrgId() != null
						&& orgService.findById(finUser.getOrgId()) != null) {
					Organization org = orgService.findById(finUser.getOrgId());
					resInfo.setCol060finDutName(org.getName());

					resInfo.setCol070finDepName(orgService.getDepNameById(org
							.getId()));

				}
			}

			infoList.add(resInfo);
		}
		return infoList;
	}
}
